package com.wx.util;

import com.baidu.aip.ocr.AipOcr;
import com.wx.model.weather.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.json.JSONException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/10/10 3:24 下午
 * @desc ：
 */
@Slf4j
@Component
public class BDUtil {
    public static final String APP_ID = "22800901";
    public static final String API_KEY = "2D0gCVQP3sRXf8qKgGdjgUCs";
    public static final String SECRET_KEY = "UXL0pNYD2OVVWGqHURGF0fZO357kmXBa";
    public static AipOcr client;

    static {
        // 初始化一个AipOcr
         client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
    }

    /**
     * 识别 图片  文字
     * @param picUrl
     * @return
     * @throws JSONException
     */
    public String imageToText(String picUrl) throws JSONException {
        String totext = null;
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

//        // 参数为本地路径
//        String image = "test.jpg";
//        JSONObject res = client.basicGeneral(image, options);
//        System.out.println(res.toString(2));
//
//        // 参数为二进制数组
//        byte[] file = readFile("test.jpg");
//        res = client.basicGeneral(file, options);
//        System.out.println(res.toString(2));

        // 通用文字识别, 图片参数为远程url图片
        org.json.JSONObject res = client.basicGeneralUrl(picUrl, options);
        /**
         * 返回成功：
         * {
         *   "words_result": [{
         *     "probability": {
         *       "average": 0.950565,
         *       "min": 0.74773,
         *       "variance": 0.005733
         *     },
         *     "words": "该公众号提供的服务出现故障,请稍后再试"
         *   }],
         *   "log_id": 1314882863493021696,
         *   "words_result_num": 1,
         *   "language": 3,
         *   "direction": 0
         * }
         *
         * 返回失败：
         *
         */
        System.out.println(res.toString(2));
        String s = res.toString(2);
        //将 字符创 转化成 JSONObject   package net.sf.json;
        JSONObject jsonObject = JSONObject.fromObject(s);
        System.out.println("jsonObject："+jsonObject);
        try{
            String error_code = jsonObject.getString("error_code");

            if(!StringUtils.isEmpty(error_code)){
                if ("216202".equals(error_code)){
                    totext = "上传的图片大小错误，现阶段我们支持的图片大小为：base64编码后小于4M，分辨率不高于4096*4096，请重新上传图片";
                }
                if ("216201".equals(error_code)){
                    totext = "上传的图片格式错误，现阶段我们支持的图片格式为：PNG、JPG、JPEG、BMP，请进行转码或更换图片";
                }
            }
        }catch (net.sf.json.JSONException e){
            e.printStackTrace();
            JSONArray words_result = jsonObject.getJSONArray("words_result");
            StringBuilder stringBuilder = new StringBuilder();
            Iterator it = words_result.iterator();
            while (it.hasNext()){
                JSONObject next = (JSONObject)it.next();
                stringBuilder.append(next.getString("words"));
            }
            log.info("imageToText:"+stringBuilder);
            totext= stringBuilder.toString();
        }
        return totext;
    }

    /**
     * 调用地址：http,https://jisuweather.api.bdymkt.com/weather/city
     * 请求方式：GET
     * 支持格式：JSON
     */
    public void getWeatherCity(){
        String Url = "https://jisuweather.api.bdymkt.com/weather/city";
        String get = CommonUtil.httpRequest(Url, "GET", null);
        System.out.println(get);

    }
    public String getWeatherByLocaltion(String location){
        String Url = "https://jisuweather.api.bdymkt.com/weather/query?location="+location;
        String url = httpUrl(Url,"GET");
        return url;
    }
    public String getWeatherByCitycode(String citycode){
        //Url: http://gwgp-n6uzuwmjrou.n.bdcloudapi.com/weather/query?citycode=101180101
        //https://jisuweather.api.bdymkt.com/weather/query
        String Url = "https://jisuweather.api.bdymkt.com/weather/query?citycode="+citycode;
        String url = httpUrl(Url,"GET");
        return url;
    }

    public String httpUrl(String Url,String RequestMethod){
        StringBuffer sb = null;
        try {
            URL url = new URL(Url);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setRequestMethod(RequestMethod);
            //设置请求头
            httpUrlConn.setRequestProperty("X-Bce-Signature","AppCode/0a7f170702e341f6b3cbd8a4e8274cb9");
            //httpUrlConn.connect();     可要    可不要
            // 获取输入流
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            // 读取返回结果
            sb = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String str = sb.toString();
        return str;

    }


    public String dealWeatherStr(String str){
        WeatherResponse response = com.alibaba.fastjson.JSONObject.parseObject(str, WeatherResponse.class);
//        System.out.println("weatherResponse:"+response);

        WeatherResult result = com.alibaba.fastjson.JSONObject.parseObject(response.getResult(), WeatherResult.class);
//        System.out.println("weatherResult:"+result);
        String todayWeather ="今天是"+result.getDate()+" "+result.getWeek()+"\r\n"+result.getCity()+"今日天气："+result.getWeather()+"，最高温度："+result.getTemphigh()+"℃"+"，最低温度："+result.getTemplow()+"℃";
        List<WeatherIndex> index = com.alibaba.fastjson.JSONObject.parseArray(result.getIndex(), WeatherIndex.class);
        StringBuffer sb1 = new StringBuffer();
        for (WeatherIndex weatherIndex : index) {
            sb1.append(weatherIndex.getIname());
            sb1.append(" : ");
            sb1.append(weatherIndex.getIvalue()+"，"+weatherIndex.getDetail());
            sb1.append("\r\n");
        }
//        System.out.println("sb1:"+sb1);

        WeatherAQI aqi = com.alibaba.fastjson.JSONObject.parseObject(result.getAqi(), WeatherAQI.class);
        WeatherAQIInfo aqiInfo = com.alibaba.fastjson.JSONObject.parseObject(aqi.getAqiInfo(), WeatherAQIInfo.class);
//        System.out.println("aqi:"+aqi);
//        System.out.println("aqiInfo:"+aqiInfo);
        String aqiStr = "空气质量信息：空气等级："+aqiInfo.getLevel()+"，"+aqi.getQuality()+"，"+aqiInfo.getMeasure()+"，"+aqiInfo.getAffect();

//        System.out.println(aqiStr);
        List<WeatherDaily> dailies = com.alibaba.fastjson.JSONObject.parseArray(result.getDaily(), WeatherDaily.class);
        StringBuffer sb2 = new StringBuffer();
        for (WeatherDaily daily : dailies) {
            DayAndNight day = com.alibaba.fastjson.JSONObject.parseObject(daily.getDay(), DayAndNight.class);
            DayAndNight night = com.alibaba.fastjson.JSONObject.parseObject(daily.getNight(), DayAndNight.class);
            sb2.append(daily.getDate()+","+daily.getWeek()+" :\r\n白天："+day.getWeather()+",最高温度"+day.getTemphigh()+"℃,"+day.getWinddirect()+","+day.getWindpower()+"\r\n夜间："+night.getWeather()+",最低温度"+night.getTemplow()+"℃,"+night.getWinddirect()+","+night.getWindpower());
            sb2.append("\r\n");
        }
//        System.out.println("sb2:"+sb2);
//        String res = todayWeather+"\r\n"+sb1+aqiStr+"\r\n"+sb2;
        String res = todayWeather+"\r\n生活小贴士：\r\n"+sb1+"一周天气预报："+"\r\n"+sb2;
        System.out.println(res);
        return res ;

    }

    /**
     * 聊天机器人
     * @param
     * @return
     */
    public String chatbot(String info){
        String Url = "https://ltjqr.api.bdymkt.com/ltjqr?info="+info;

        String url = httpUrl(Url,"POST");
        return dealWeatherStr(url);
    }



}
